<?php

defined('WEBWI_ROOT_PATH') or die('Restricted access');

class WebwiLoad
{
	
	 static function load($name, $type = "system")
	 {
		  static $loaded;
		  
		  $name = strtolower($name);
		  $type = empty($type) ? 'system' : $type;
		  
		  if (isset($loaded[$type][$name])) {
			  return $loaded[$type][$name];
		  }
		  
		  if (class_exists($name)) {
            $loaded[$type][$name] = true;
            return true;
        }

		switch ($type) {
			case 'class':
            case 'system':
                $type = 'system';
				$isloaded = WebwiLoad::loadSystem($name);
            break;
			default:
                $isloaded = WebwiLoad::loadPlugin($name, $type);
            break;
        }
        $loaded[$type][$name] = $isloaded;
        return $loaded[$type][$name];
    }
	
	
	static private function loadSystem($name)
    {
        static $fdata;
		
		if (!isset($fdata)) {
            $fdata = WebwiLoad::loadSystemClassmap();
        }
		
		if (isset($fdata[$name])) {
            // * versuche aus Datenmap zu laden
            require $fdata[$name];
            if (class_exists($name) && method_exists($name, '__autoload')) {
                call_user_func(array($name, '__autoload'));
            }
            return true;
        } elseif (file_exists($file = WEBWI_ROOT_PATH . '/system/classes/' . $name . '.php')) {
            // versuche direkt die Datei einzubinden
            include_once $file;
            $class = 'Webwi' . ucfirst($name);
            if (class_exists($class)) {
                return $class;
            } else {
                trigger_error('Class ' . $name . ' not found in file ' . __FILE__ . 'at line ' . __LINE__, E_USER_WARNING);
            }
        }
        return false;
    }
		
	static function loadSystemClassmap()
    {
        return array(
            'webwidb' => WEBWI_ROOT_PATH . '/system/classes/database.php',
			'webwilogger' => WEBWI_ROOT_PATH . '/system/classes/logger.php',
            'webwihtml' => WEBWI_ROOT_PATH . '/system/classes/HTML.php',
			'webwisession' => WEBWI_ROOT_PATH . '/system/classes/session.php',
			'webwisecurity' => WEBWI_ROOT_PATH . '/system/classes/security.php',
			'webwinotify' => WEBWI_ROOT_PATH . '/system/classes/notification.php',
			'webwierror'	=> WEBWI_ROOT_PATH .'/system/classes/webwierror.php',
		);
    }
		
	static private function loadPlugin($name, $plugin = null)
    {
        if (empty($plugin)) {
            return false;
        }
        if (file_exists($file = WEBWI_ROOT_PATH . '/system/' . $plugin . '/' . $name . '.php')) {
            include $file;
            if (class_exists(ucfirst($dirname) . ucfirst($name))) {
                return true;
            }
        }
        return false;
    }	
	
} // CLASSEND	
	
		
	if (!defined('WEBWI_AUTOLOAD')) {
		define('WEBWI_AUTOLOAD', true);
		spl_autoload_register(array('WebwiLoad', 'load'));
	}
		

?>